package com.tetris.ui;

import com.tetris.block.Block;
import com.tetris.logic.TetrisGame;
import com.tetris.rule.GameRules;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.*;

/**
 * 游戏UI界面类，使用Java Swing实现
 */
public class TetrisUI extends JFrame {
    private final TetrisGame game;
    private final GamePanel gamePanel;
    private final SidePanel sidePanel;
    private final Timer refreshTimer;
    private final Timer dropTimer;
    private int refreshDelay = 50; // 刷新延迟，毫秒，降低延迟提高刷新率
    private int dropDelay = 300; // 下落延迟，毫秒，保持原来的下落速度
    private int highScore = 0; // 最高分记录
    private static final String HIGH_SCORE_FILE = "tetris_high_score.txt"; // 最高分保存文件

    public TetrisUI() {
        // 初始化游戏
        game = new TetrisGame(10, 20);
        
        // 加载历史最高分
        loadHighScore();

        // 设置窗口
        setTitle("俄罗斯方块");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        // 创建游戏面板
        gamePanel = new GamePanel();

        // 创建侧边面板
        sidePanel = new SidePanel();

        // 添加键盘监听
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (game.isGameOver()) {
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        game.startNewGame();
                        startGame();
                        repaint();
                    }
                    return;
                }

                switch (e.getKeyCode()) {
                    case KeyEvent.VK_LEFT:
                        game.moveBlock(GameRules.Direction.LEFT);
                        break;
                    case KeyEvent.VK_RIGHT:
                        game.moveBlock(GameRules.Direction.RIGHT);
                        break;
                    case KeyEvent.VK_DOWN:
                        game.moveBlock(GameRules.Direction.DOWN);
                        break;
                    case KeyEvent.VK_UP:
                        game.rotateBlock(GameRules.Rotation.CLOCKWISE);
                        break;
                    case KeyEvent.VK_SPACE:
                        hardDrop();
                        break;
                    case KeyEvent.VK_P:
                        pauseGame();
                        break;
                }

                repaint();
            }
        });

        // 创建刷新计时器 - 负责界面刷新
        refreshTimer = new Timer(refreshDelay, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                repaint();
            }
        });

        // 创建下落计时器 - 负责方块下落
        dropTimer = new Timer(dropDelay, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!game.moveBlock(GameRules.Direction.DOWN)) {
                    // 如果方块无法下落，则刷新界面
                    repaint();
                }

                // 检查游戏是否结束
                if (game.isGameOver()) {
                    refreshTimer.stop();
                    dropTimer.stop();
                    
                    // 检查是否打破最高分
                    checkAndUpdateHighScore();
                    
                    JOptionPane.showMessageDialog(TetrisUI.this,
                            "游戏结束！得分: " + game.getScore(),
                            "游戏结束",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });

        // 设置布局
        setLayout(new BorderLayout());
        add(gamePanel, BorderLayout.CENTER);
        add(sidePanel, BorderLayout.EAST);

        // 调整窗口大小
        pack();
        setLocationRelativeTo(null);

        // 开始游戏
        startGame();
    }
    
    // 加载历史最高分
    private void loadHighScore() {
        File file = new File(HIGH_SCORE_FILE);
        if (file.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line = reader.readLine();
                if (line != null) {
                    try {
                        highScore = Integer.parseInt(line.trim());
                    } catch (NumberFormatException e) {
                        highScore = 0;
                    }
                }
            } catch (IOException e) {
                highScore = 0;
            }
        }
    }
    
    // 检查并更新最高分
    private void checkAndUpdateHighScore() {
        if (game.getScore() > highScore) {
            highScore = game.getScore();
            saveHighScore();
        }
    }
    
    // 保存最高分
    private void saveHighScore() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(HIGH_SCORE_FILE))) {
            writer.write(String.valueOf(highScore));
        } catch (IOException e) {
            System.err.println("保存最高分失败: " + e.getMessage());
        }
    }

    // 获取当前最高分
    public int getHighScore() {
        return highScore;
    }

    // 硬降（方块直接落到底部）
    private void hardDrop() {
        while (game.moveBlock(GameRules.Direction.DOWN)) {
            // 继续下落
        }
    }

    // 开始游戏
    private void startGame() {
        refreshTimer.start();
        dropTimer.start();
    }

    // 暂停游戏
    private void pauseGame() {
        if (refreshTimer.isRunning() && dropTimer.isRunning()) {
            refreshTimer.stop();
            dropTimer.stop();
        } else {
            refreshTimer.start();
            dropTimer.start();
        }
    }

    // 游戏面板
    private class GamePanel extends JPanel {
        private static final int BLOCK_SIZE = 30;

        public GamePanel() {
            setPreferredSize(new Dimension(game.getWidth() * BLOCK_SIZE, game.getHeight() * BLOCK_SIZE));
            setBackground(Color.BLACK);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // 绘制网格
            drawGrid(g);

            // 绘制当前方块
            drawBlock(g, game.getCurrentBlock());

            // 如果游戏结束，显示提示
            if (game.isGameOver()) {
                drawGameOver(g);
            }
        }

        private void drawGrid(Graphics g) {
            int[][] grid = game.getGrid();

            for (int i = 0; i < game.getHeight(); i++) {
                for (int j = 0; j < game.getWidth(); j++) {
                    if (grid[i][j] != 0) {
                        drawBlockCell(g, j, i, Color.GRAY);
                    }
                }
            }
        }

        private void drawBlock(Graphics g, Block block) {
            if (block == null) return;

            int[][] shape = block.getShape();
            int x = block.getX();
            int y = block.getY();

            for (int i = 0; i < shape.length; i++) {
                for (int j = 0; j < shape[i].length; j++) {
                    if (shape[i][j] != 0) {
                        drawBlockCell(g, x + j, y + i, block.getColor());
                    }
                }
            }
        }

        private void drawBlockCell(Graphics g, int x, int y, Color color) {
            if (y < 0) return; // 不绘制屏幕外的方块

            g.setColor(color);
            g.fillRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);

            g.setColor(Color.WHITE);
            g.drawRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
        }

        private void drawGameOver(Graphics g) {
            // 设置支持中文的字体
            g.setFont(new Font("SimHei", Font.BOLD, 30));
            g.setColor(Color.RED);
            FontMetrics metrics = g.getFontMetrics();
            String text = "游戏结束";
            int x = (getWidth() - metrics.stringWidth(text)) / 2;
            int y = getHeight() / 2;
            g.drawString(text, x, y);

            g.setFont(new Font("SimHei", Font.PLAIN, 16));
            metrics = g.getFontMetrics();
            text = "按Enter键重新开始";
            x = (getWidth() - metrics.stringWidth(text)) / 2;
            y = getHeight() / 2 + 30;
            g.drawString(text, x, y);
        }
    }

    // 侧边面板
    private class SidePanel extends JPanel {
        private static final int BLOCK_SIZE = 25;
        private static final int PANEL_WIDTH = 200;
        private final int PANEL_HEIGHT; // 修改为非静态字段

        public SidePanel() {
            // 在构造函数中初始化PANEL_HEIGHT
            PANEL_HEIGHT = game.getHeight() * GamePanel.BLOCK_SIZE;
            setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
            setBackground(Color.DARK_GRAY);
            setBorder(BorderFactory.createLineBorder(Color.WHITE));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // 设置支持中文的字体
            g.setFont(new Font("SimHei", Font.BOLD, 20));
            g.setColor(Color.WHITE);

            // 绘制分数
            drawScore(g);

            // 绘制下一个方块
            drawNextBlock(g);

            // 绘制操作说明
            drawInstructions(g);
        }

        private void drawScore(Graphics g) {
            g.drawString("分数: " + game.getScore(), 20, 30);
            g.drawString("最高分: " + highScore, 20, 60);
        }

        private void drawNextBlock(Graphics g) {
            Block nextBlock = game.getNextBlock();
            if (nextBlock == null) return;

            g.drawString("下一个:", 20, 100);

            int[][] shape = nextBlock.getShape();
            int startX = (PANEL_WIDTH - shape[0].length * BLOCK_SIZE) / 2;
            int startY = 120;

            for (int i = 0; i < shape.length; i++) {
                for (int j = 0; j < shape[i].length; j++) {
                    if (shape[i][j] != 0) {
                        g.setColor(nextBlock.getColor());
                        g.fillRect(startX + j * BLOCK_SIZE, startY + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);

                        g.setColor(Color.WHITE);
                        g.drawRect(startX + j * BLOCK_SIZE, startY + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
                    }
                }
            }
        }

        private void drawInstructions(Graphics g) {
            // 设置支持中文的字体
            g.setFont(new Font("SimHei", Font.PLAIN, 14));

            int startY = 250;
            int lineHeight = 25;

            g.drawString("操作说明:", 20, startY);
            g.drawString("← →: 左右移动", 20, startY + lineHeight);
            g.drawString("↓: 加速下落", 20, startY + 2 * lineHeight);
            g.drawString("↑: 顺时针旋转", 20, startY + 3 * lineHeight);
            g.drawString("空格: 硬降", 20, startY + 4 * lineHeight);
            g.drawString("P: 暂停", 20, startY + 5 * lineHeight);
            g.drawString("Enter: 重新开始", 20, startY + 6 * lineHeight);
        }
    }

    public static void main(String[] args) {
        // 设置系统属性确保中文显示正常
        System.setProperty("file.encoding", "UTF-8");
        
        SwingUtilities.invokeLater(() -> {
            new TetrisUI().setVisible(true);
        });
    }
}